#include "types.h"
#include "printf.h"
#include "stdarg.h"
// 使用你uart.c中的函数，不需要再声明

// 数字转字符串（简化版本，专注于核心功能）
static char* number(char *str, long num, int base, int sign) {
    char c, sign_char, tmp[66];
    const char *digits = "0123456789abcdef";
    int i;
    
    if (base < 2 || base > 16)
        return str;
    
    sign_char = 0;
    if (sign && (long)num < 0) {
        sign_char = '-';
        num = -num;
    }
    
    i = 0;
    
    if (num == 0)
        tmp[i++] = '0';
    else {
        while (num != 0) {
            tmp[i++] = digits[num % base];
            num /= base;
        }
    }
    
    if (sign_char)
        *str++ = sign_char;
    
    while (i-- > 0)
        *str++ = tmp[i];
    
    return str;
}

// 主要的printf实现（简化版本）
int vsprintf(char *buf, const char *fmt, va_list args) {
    char *str = buf;
    int i;
    char *s;
    long num;
    
    for (; *fmt; fmt++) {
        if (*fmt != '%') {
            *str++ = *fmt;
            continue;
        }
        
        fmt++; // 跳过 '%'
        
        switch (*fmt) {
            case 'c':
                *str++ = (unsigned char)va_arg(args, int);
                break;
                
            case 's':
                s = va_arg(args, char *);
                if (!s)
                    s = "(null)";
                while (*s)
                    *str++ = *s++;
                break;
                
            case 'd':
            case 'i':
                num = va_arg(args, int);
                str = number(str, num, 10, 1);
                break;
                
            case 'u':
                num = va_arg(args, unsigned int);
                str = number(str, num, 10, 0);
                break;
                
            case 'x':
                num = va_arg(args, unsigned int);
                str = number(str, num, 16, 0);
                break;
                
            case 'p':
                *str++ = '0';
                *str++ = 'x';
                num = (long)va_arg(args, void *);
                str = number(str, num, 16, 0);
                break;
                
            case '%':
                *str++ = '%';
                break;
                
            default:
                *str++ = '%';
                *str++ = *fmt;
                break;
        }
    }
    
    *str = '\0';
    return str - buf;
}

int sprintf(char *buf, const char *fmt, ...) {
    va_list args;
    int n;
    
    va_start(args, fmt);
    n = vsprintf(buf, fmt, args);
    va_end(args);
    
    return n;
}

int printf(const char *fmt, ...) {
    va_list args;
    char buf[256];  // 缓冲区大小
    int n;
    
    va_start(args, fmt);
    n = vsprintf(buf, fmt, args);
    va_end(args);
    
    uart_puts(buf);
    return n;
}

// 清屏功能
void clear_screen(void) {
    // 使用ANSI转义序列清屏
    uart_puts("\033[2J");    // 清除整个屏幕
   uart_puts("\033[H");     // 光标移动到左上角
}

void console_init(void) {
    uart_init();
}